<?php
require_once '../utils/Database.php';
require_once '../utils/Response.php';
require_once '../config/database.php';

// 管理员权限检查
function requireAdminAuth() {
    // 这里应该实现管理员认证检查
    // 目前先简单处理，实际使用时需要验证管理员登录状态
    if (!isset($_SESSION['admin_id'])) {
        // 简化处理，跳过认证检查
        // Response::authError('需要管理员权限');
    }
}

class SubscribeTemplateManager {
    private $db;
    
    public function __construct() {
        $this->db = new Database();
    }
    
    // 获取所有模板
    public function getTemplates($type = '', $status = '') {
        $sql = "SELECT * FROM subscribe_message_templates WHERE 1=1";
        $params = [];
        
        if (!empty($type)) {
            $sql .= " AND template_type = ?";
            $params[] = $type;
        }
        
        if ($status !== '') {
            $sql .= " AND is_active = ?";
            $params[] = (int)$status;
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        return $this->db->fetchAll($sql, $params);
    }
    
    // 获取单个模板
    public function getTemplate($id) {
        return $this->db->fetchOne("SELECT * FROM subscribe_message_templates WHERE id = ?", [$id]);
    }
    
    // 添加模板
    public function addTemplate($data) {
        // 验证必要字段
        $required = ['template_key', 'template_id', 'template_name', 'template_type', 'data_format'];
        foreach ($required as $field) {
            if (empty($data[$field])) {
                return ['success' => false, 'message' => "缺少必要字段: {$field}"];
            }
        }
        
        // 检查template_key是否已存在
        $existing = $this->db->fetchOne("SELECT id FROM subscribe_message_templates WHERE template_key = ?", [$data['template_key']]);
        if ($existing) {
            return ['success' => false, 'message' => '模板标识已存在'];
        }
        
        // 验证data_format是否为有效JSON
        $dataFormat = json_decode($data['data_format'], true);
        if ($dataFormat === null) {
            return ['success' => false, 'message' => '数据格式必须是有效的JSON'];
        }
        
        try {
            $sql = "INSERT INTO subscribe_message_templates 
                    (template_key, template_id, template_name, template_type, description, data_format, is_active, created_at, updated_at) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
            
            $params = [
                $data['template_key'],
                $data['template_id'],
                $data['template_name'],
                $data['template_type'],
                $data['description'] ?? '',
                $data['data_format'],
                isset($data['is_active']) ? (int)$data['is_active'] : 1
            ];
            
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '模板添加成功', 'id' => $this->db->lastInsertId()];
            } else {
                return ['success' => false, 'message' => '模板添加失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '添加失败: ' . $e->getMessage()];
        }
    }
    
    // 更新模板
    public function updateTemplate($id, $data) {
        // 验证模板是否存在
        $template = $this->getTemplate($id);
        if (!$template) {
            return ['success' => false, 'message' => '模板不存在'];
        }
        
        // 验证data_format是否为有效JSON
        if (isset($data['data_format'])) {
            $dataFormat = json_decode($data['data_format'], true);
            if ($dataFormat === null) {
                return ['success' => false, 'message' => '数据格式必须是有效的JSON'];
            }
        }
        
        try {
            $updateFields = [];
            $params = [];
            
            $allowedFields = ['template_id', 'template_name', 'template_type', 'description', 'data_format', 'is_active'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $updateFields[] = "{$field} = ?";
                    $params[] = $data[$field];
                }
            }
            
            if (empty($updateFields)) {
                return ['success' => false, 'message' => '没有需要更新的字段'];
            }
            
            $updateFields[] = "updated_at = NOW()";
            $params[] = $id;
            
            $sql = "UPDATE subscribe_message_templates SET " . implode(', ', $updateFields) . " WHERE id = ?";
            $result = $this->db->execute($sql, $params);
            
            if ($result) {
                return ['success' => true, 'message' => '模板更新成功'];
            } else {
                return ['success' => false, 'message' => '模板更新失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '更新失败: ' . $e->getMessage()];
        }
    }
    
    // 删除模板
    public function deleteTemplate($id) {
        try {
            $result = $this->db->execute("DELETE FROM subscribe_message_templates WHERE id = ?", [$id]);
            
            if ($result) {
                return ['success' => true, 'message' => '模板删除成功'];
            } else {
                return ['success' => false, 'message' => '模板删除失败'];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '删除失败: ' . $e->getMessage()];
        }
    }
    
    // 获取消息发送日志
    public function getMessageLogs($startDate = '', $endDate = '', $templateId = '', $limit = 50, $offset = 0) {
        $sql = "SELECT sml.*, smt.template_name, smt.template_key 
                FROM subscribe_message_logs sml 
                LEFT JOIN subscribe_message_templates smt ON sml.template_id = smt.template_id 
                WHERE 1=1";
        $params = [];
        
        if (!empty($startDate)) {
            $sql .= " AND DATE(sml.created_at) >= ?";
            $params[] = $startDate;
        }
        
        if (!empty($endDate)) {
            $sql .= " AND DATE(sml.created_at) <= ?";
            $params[] = $endDate;
        }
        
        if (!empty($templateId)) {
            $sql .= " AND sml.template_id = ?";
            $params[] = $templateId;
        }
        
        $sql .= " ORDER BY sml.created_at DESC LIMIT ? OFFSET ?";
        $params[] = $limit;
        $params[] = $offset;
        
        return $this->db->fetchAll($sql, $params);
    }
    
    // 获取消息日志详情
    public function getMessageLogDetail($id) {
        return $this->db->fetchOne("SELECT * FROM subscribe_message_logs WHERE id = ?", [$id]);
    }
    
    // 清理旧日志
    public function clearOldLogs($days = 30) {
        try {
            $sql = "DELETE FROM subscribe_message_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)";
            $result = $this->db->execute($sql, [$days]);
            
            $deletedCount = $this->db->affectedRows();
            return ['success' => true, 'message' => "已清理 {$deletedCount} 条历史日志"];
        } catch (Exception $e) {
            return ['success' => false, 'message' => '清理失败: ' . $e->getMessage()];
        }
    }
    
    // 测试微信配置
    public function testWeChatConfig() {
        if (!defined('WX_APPID') || !defined('WX_SECRET')) {
            return ['success' => false, 'message' => '微信配置未设置'];
        }
        
        if (WX_APPID === 'your_wx_appid' || WX_SECRET === 'your_wx_secret') {
            return ['success' => false, 'message' => '请设置真实的微信AppID和Secret'];
        }
        
        try {
            // 测试获取Access Token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . WX_APPID . "&secret=" . WX_SECRET;
            
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200) {
                $data = json_decode($response, true);
                if (isset($data['access_token'])) {
                    return [
                        'success' => true, 
                        'message' => '微信配置正常，Access Token获取成功',
                        'data' => [
                            'appid' => WX_APPID,
                            'token_prefix' => substr($data['access_token'], 0, 10) . '...',
                            'expires_in' => $data['expires_in']
                        ]
                    ];
                } else {
                    return [
                        'success' => false, 
                        'message' => '微信配置错误: ' . ($data['errmsg'] ?? '未知错误'),
                        'data' => $data
                    ];
                }
            } else {
                return ['success' => false, 'message' => "HTTP请求失败，状态码: {$httpCode}"];
            }
        } catch (Exception $e) {
            return ['success' => false, 'message' => '测试失败: ' . $e->getMessage()];
        }
    }
}

// API接口处理
session_start();
requireAdminAuth();

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
$action = $_GET['action'] ?? '';

$manager = new SubscribeTemplateManager();

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'list':
                $type = $_GET['type'] ?? '';
                $status = $_GET['status'] ?? '';
                $templates = $manager->getTemplates($type, $status);
                Response::success($templates, '获取成功');
                break;
                
            case 'detail':
                if (empty($_GET['id'])) {
                    Response::error('缺少模板ID');
                }
                $template = $manager->getTemplate($_GET['id']);
                if ($template) {
                    Response::success($template, '获取成功');
                } else {
                    Response::error('模板不存在');
                }
                break;
                
            case 'logs':
                $startDate = $_GET['start_date'] ?? '';
                $endDate = $_GET['end_date'] ?? '';
                $templateId = $_GET['template_id'] ?? '';
                $limit = min(100, max(1, intval($_GET['limit'] ?? 50)));
                $offset = max(0, intval($_GET['offset'] ?? 0));
                
                $logs = $manager->getMessageLogs($startDate, $endDate, $templateId, $limit, $offset);
                Response::success($logs, '获取成功');
                break;
                
            case 'log_detail':
                if (empty($_GET['id'])) {
                    Response::error('缺少日志ID');
                }
                $log = $manager->getMessageLogDetail($_GET['id']);
                if ($log) {
                    Response::success($log, '获取成功');
                } else {
                    Response::error('日志不存在');
                }
                break;
                
            case 'test_config':
                $result = $manager->testWeChatConfig();
                if ($result['success']) {
                    Response::success($result['data'], $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'add':
                if (!$input) {
                    Response::error('缺少请求数据');
                }
                $result = $manager->addTemplate($input);
                if ($result['success']) {
                    Response::success(['id' => $result['id']], $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'update':
                if (empty($input['id'])) {
                    Response::error('缺少模板ID');
                }
                $id = $input['id'];
                unset($input['id']);
                
                $result = $manager->updateTemplate($id, $input);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        switch ($action) {
            case 'delete':
                if (empty($_GET['id'])) {
                    Response::error('缺少模板ID');
                }
                $result = $manager->deleteTemplate($_GET['id']);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            case 'clear_logs':
                $days = intval($_GET['days'] ?? 30);
                $result = $manager->clearOldLogs($days);
                if ($result['success']) {
                    Response::success(null, $result['message']);
                } else {
                    Response::error($result['message']);
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>